package com.znf4.permission;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.znf4.permission.entity.Function;
import com.znf4.permission.entity.Role;
import com.znf4.permission.server.PermissionServer;
import com.znf4.user.info.entity.UserInfo;

/*import com.platform.entity.Function;
import com.platform.entity.Role;
import com.platform.entity.User;
import com.platform.service.HelpService;*/



/**
 * 
 * @author agui
 * @description 自定义的验证Realm
 * 	登录时的账号验证..
 * 	访问时的权限验证..
 *2015年10月12日  下午3:32:33
 */
public class MyRealm extends AuthorizingRealm{  
    
    @Autowired
    private  PermissionServer permissionServer;
    
    
    /** @description 添加角色	
     * @param username
     * @param info
     *2015年10月12日  下午2:40:39
     *返回类型:void	
     */
	private void addRole(String id , SimpleAuthorizationInfo info) {
		
		Map<String , String > map = new HashMap<>() ;
		map.put("user_id", id) ;
		List<Role> roles = permissionServer.queryRoleByUserId(map);
		 //角色名的集合  
        Set<String> roleSet = new HashSet<String>();  
        //权限名的集合  
        Set<String> permissions = new HashSet<String>();  

		for (Role role : roles) {
			roleSet.add(role.getName());  
			addPermission(role.getName() , permissions );
			System.out.println("角色 ：" + role.getName());
		}
		
		info.addRoles(roleSet);  
		info.addStringPermissions(permissions);  
		
	}

    /**
     * @description 添加权限	
     * @param username
     * @param info
     * @return
     *2015年10月12日  下午2:42:15
     *返回类型:SimpleAuthorizationInfo
     */
	private void addPermission(String id , Set<String> permissions) {
		
		Map<String , String > map = new HashMap<>() ;
		map.put("role_id", id) ;
		List<Function> functions = permissionServer.queryFunctionByRoleId(map) ;
		for (Function function : functions) {
			permissions.add(function.getFunction()); // 添加权限
			System.out.println(" 路径 ：" + function.getFunction());
		}
	} 
  
    
    /**
     * 获取授权信息
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {  
        //用户名  
        String username = (String) principals.fromRealm(getName()).iterator().next(); 
        
        //根据用户名来添加相应的权限和角色
        if(!StringUtils.isEmpty(username)){
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            addRole(username, info);
            return info;
        }
         
        return null;  
    }

   
   /** 
    * 登录验证 
    */  
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
			throws AuthenticationException {
		System.out.println("登陆认证功能启用");
		// 令牌——基于用户名和密码的令牌
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		// 令牌中可以取出用户名密码
		String accountName = token.getUsername();
		// 让shiro框架去验证账号密码
		// if(!StringUtils.isEmpty(accountName)){
		/*UserInfo user = helpService.userLgoin(accountName);
		if (user != null) {
			return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName()); // getName()
		}*/
		// }

		return null;
	}  
	
	//清除缓存
    public void clearCached() {
        PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
        super.clearCache(principals);
    }
    
}
